package mbp.gui.panels;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.Color;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JScrollPane;
import java.awt.Component;
import javax.swing.JButton;
import java.awt.Font;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import mbp.base.GuiFunction;
import mbp.base.ResourceType;
import mbp.core.ResourceTypeBuilder;
import mbp.core.ResourceUtility;
import mbp.exceptions.InvalidEnumTypeException;
import mbp.exceptions.InvalidFeatureNameException;
import mbp.exceptions.InvalidResourceTypeException;
import mbp.gui.frames.MbpManagerGui;

import javax.swing.border.TitledBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.UIManager;

import org.apache.log4j.Logger;

public class ResourceUtilityGui extends JPanel implements ActionListener
{
	private JComboBox cmbUtilityFc;
	private JComboBox cmbTypesXml;
	private JButton btnSet, btnCalculate, btnCreateUt;
	
	private ResourceUtility utilityFunction;
    private HashMap<String, ResourceUtility> utilityFunctionStore;
    private MbpManagerGui mbpManagerGui;
    private JPanel panel_1;
    private JPanel panel_2;
    private JTextField txtAgenName;
    private JButton btnSend;
    private JLabel label_3;
    
    private ResourceUtilityEditPanel ruEditPanel;
    
    private Logger logger = Logger.getLogger(this.getClass());
    //private JButton btnToClient;
	
	public ResourceUtilityGui(MbpManagerGui mbpManagerGui) 
	{
		setLayout(null);
		
		this.mbpManagerGui = mbpManagerGui;
		utilityFunctionStore = new HashMap<String, ResourceUtility>();
		
		ruEditPanel = new ResourceUtilityEditPanel(GuiFunction.EDITOR, null);
		ruEditPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Resource utility", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 70, 213)));
		ruEditPanel.setBounds(310, 12, 290, 231);
		add(ruEditPanel);
		
		
		JPanel panel_0 = new JPanel();
		panel_0.setLayout(null);
		panel_0.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Resource Type Fom XML", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
		panel_0.setBounds(10, 11, 290, 70);
		add(panel_0);
		
		cmbTypesXml = new JComboBox();
		cmbTypesXml.setBounds(10, 39, 125, 20);
		panel_0.add(cmbTypesXml);
		
		btnCreateUt = new JButton("Create");
		btnCreateUt.setName("CREATE");
		btnCreateUt.setFont(new Font("Arial", Font.PLAIN, 11));
		btnCreateUt.setBounds(145, 36, 80, 23);
		panel_0.add(btnCreateUt);
		
		JLabel label_2 = new JLabel("Resource type");
		label_2.setBounds(10, 22, 100, 14);
		panel_0.add(label_2);
		
		panel_1 = new JPanel();
		panel_1.setBorder(new TitledBorder(null, "Active utility function", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel_1.setBounds(10, 92, 290, 70);
		add(panel_1);
		panel_1.setLayout(null);
		
		cmbUtilityFc = new JComboBox();
		cmbUtilityFc.setBounds(10, 39, 125, 20);
		panel_1.add(cmbUtilityFc);
		
		btnCalculate = new JButton("Calculate");
		btnCalculate.setBounds(147, 36, 80, 23);
		panel_1.add(btnCalculate);
		btnCalculate.setName("UT_CALC");
		btnCalculate.setFont(new Font("Arial", Font.PLAIN, 11));
		
//		btnToClient = new JButton("->");
//		btnToClient.setFont(new Font("Dialog", Font.PLAIN, 11));
//		btnToClient.setBounds(237, 36, 43, 23);
//		panel_1.add(btnToClient);
//		btnToClient.addActionListener(this);
		
		btnCalculate.addActionListener(this);
		
		panel_2 = new JPanel();
		panel_2.setLayout(null);
		panel_2.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Send utility function", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
		panel_2.setBounds(10, 173, 290, 70);
		add(panel_2);
		
		txtAgenName = new JTextField();
		txtAgenName.setColumns(10);
		txtAgenName.setBounds(10, 39, 125, 20);
		panel_2.add(txtAgenName);
		
		btnSend = new JButton("Send");
		btnSend.setFont(new Font("Arial", Font.PLAIN, 11));
		btnSend.setBounds(145, 38, 80, 23);
		panel_2.add(btnSend);
		
		label_3 = new JLabel("Agent name");
		label_3.setBounds(10, 24, 80, 14);
		panel_2.add(label_3);
		btnCreateUt.addActionListener(this);
		//btnSet.addActionListener(this);
		btnSend.addActionListener(this);
		
		cmbUtilityFc.addItemListener(new ItemListener() {
			
			@Override
			public void itemStateChanged(ItemEvent e) 
			{
				int index = cmbUtilityFc.getSelectedIndex();
				String key = (String)cmbUtilityFc.getItemAt(index);
				if(index == -1)
				{
					utilityFunction = null;
					ruEditPanel.clear();
					return;
				}
				loadResourceUtility(utilityFunctionStore.get(key));
				// TODO Auto-generated method stub
				
			}
		});
	}
	
	public ArrayList<ResourceUtility> getUtilitiesList()
	{
		ArrayList<ResourceUtility> utilityList = new ArrayList<ResourceUtility>(utilityFunctionStore.values());
		return utilityList;
	}
	
	public void LoadResourceTypeList(List<String> types)
	{
		Iterator<String> it = types.iterator();
		
		while(it.hasNext())
		{
			String type = it.next();
			cmbTypesXml.addItem(type);
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) 
	{
		if(e.getSource() == btnCreateUt)
		{
			ResourceTypeBuilder typeBuilder = new ResourceTypeBuilder("");
			ResourceType tmpType = typeBuilder.GetResourceType((String)cmbTypesXml.getSelectedItem());
			ResourceUtility utf = new ResourceUtility(tmpType);				
			AddUtilityFunction(utf);
			return;
		}
		
		if(e.getSource() == btnSet)
		{
			ruEditPanel.setUtilityFunction();
			return;
		}
		
		if(e.getSource() == btnCalculate)
		{
			try 
			{
				float utlt = utilityFunction.calculateUtility(mbpManagerGui.getActiveResource());
				JOptionPane.showMessageDialog((Component) e.getSource(), "Value: " + utlt, "Calculated utility for active resource", JOptionPane.INFORMATION_MESSAGE);
			}
			catch (InvalidResourceTypeException e1) 
			{
				JOptionPane.showMessageDialog((Component) e.getSource(), e1.getMessage(), "InvalidResourceTypeException", JOptionPane.ERROR_MESSAGE);
				//e1.printStackTrace();
			}
			catch(NullPointerException e2)
			{
				JOptionPane.showMessageDialog((Component) e.getSource(), "No active resource!!! See Resource builder tab", "NullPointerException", JOptionPane.ERROR_MESSAGE);
			}
			
			return;
		}
		
		if(e.getSource() == btnSend)
		{
			//JOptionPane.showMessageDialog((Component) e.getSource(), "Not implemented yet.", "Warning", JOptionPane.WARNING_MESSAGE);
			mbpManagerGui.myAgent.SendResourceUtility(utilityFunction, txtAgenName.getText());
			return;
		}
		
//		if(e.getSource() == btnToClient)
//		{
//			if(utilityFunction != null)
//			{
//				mbpManagerGui.businessAgentGui.addResourceUtility(deleteActiveObject());
//			}
//		}
		
	}
	
	public void AddUtilityFunction(ResourceUtility utl)
	{
		int items = utilityFunctionStore.size();
		String name = utl.getResourceTypeName();
		name = name + " [" + items + "]";
		utilityFunctionStore.put(name, utl);
		cmbUtilityFc.addItem(name);
		cmbUtilityFc.setSelectedItem(name);
		
		loadResourceUtility(utl);
	}
	
	
	public void loadResourceUtility(ResourceUtility utl)
	{
		ruEditPanel.LoadUtilityFunction(utl);
		this.utilityFunction = utl;
	}
	
	public ResourceUtility deleteActiveObject()
	{
		int index = cmbUtilityFc.getSelectedIndex();
		ResourceUtility rcu = null;
		if(index != -1)
		{
			String key = (String)cmbUtilityFc.getItemAt(index);
			rcu = utilityFunctionStore.remove(key);
			//cmbResources.removeAllItems();
			cmbUtilityFc.removeItemAt(index);
			//cmbResources.validate();
		}
		return rcu;
	}
}
